package org.example.classtopia.Service.Impl;

import org.example.classtopia.Mapper.PostLikeMapper;
import org.example.classtopia.Mapper.PostMapper;
import org.example.classtopia.Mapper.UserMapper;
import org.example.classtopia.Mapper.UserMassageMapper;
import org.example.classtopia.Model.Entity.Post;
import org.example.classtopia.Model.Entity.PostLike;
import org.example.classtopia.Model.Entity.UserMessage;
import org.example.classtopia.Service.PostLikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class PostLikeServiceImpl implements PostLikeService {

    @Autowired
    private PostLikeMapper postLikeMapper;

    @Autowired
    private PostMapper postMapper;

    @Autowired
    private UserMassageMapper userMassageMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean likePost(Long userId, Long postId) {
        // 校验帖子是否存在
        Post post = postMapper.selectPostById(postId);
        if (post == null) {

            throw new IllegalArgumentException("帖子不存在，无法点赞");
        }

        // 先判断是否已经点赞
        PostLike existing = postLikeMapper.findByUserAndPost(userId, postId);
        if (existing != null) {
            return false; // 已点赞，不能重复点赞
        }
        PostLike like = new PostLike();
        like.setUserId(userId);
        like.setPostId(postId);
        like.setCreatedAt(LocalDateTime.now());

        UserMessage userMessage = new UserMessage();
        userMessage.setUserId(postMapper.getUserIdByPostId(postId));
        userMessage.setPostId(postId);
        userMessage.setContent("用户" + userMapper.FindDataByID(Math.toIntExact(userId)).getNickname() +
                "点赞了你的帖子");
        userMessage.setMessageType("postLike");
        userMessage.setIsRead(0);
        userMessage.setTime(like.getCreatedAt());
        userMassageMapper.InsertUserMessage(userMessage);

        int rows = postLikeMapper.insert(like);
        if (rows > 0) {
            postMapper.incrementLikeCount(postId); // 点赞数加1
            return true;
        }
        return false;
        //return rows > 0;
    }

    @Override
    public boolean unlikePost(Long userId, Long postId) {
        int rows = postLikeMapper.deleteByUserAndPost(userId, postId);
        if (rows > 0) {
            userMassageMapper.DeletePostLikeUserMessage(userId,postId);
            postMapper.decrementLikeCount(postId); // 点赞数减1
            return true;
        }
        return false;
        //return rows > 0;
    }

    @Override
    public boolean hasLiked(Long userId, Long postId) {
        PostLike existing = postLikeMapper.findByUserAndPost(userId, postId);
        return existing != null;
    }

    @Override
    public int countLikes(Long postId) {
        return postLikeMapper.countByPostId(postId);
    }
}

